import easygui as g
import urllib.request

#0
#urlopen()的timeout，用于设置请求超时时间(秒)

#1
#print(response.getcode())
#响应对象获取code

#2
# 毫无疑问 post get

#3
# 毫无疑问，客户端发起请求，服务器响应

#4
#user-agent客户端信息

#5
#当urlopen()中data参数被赋值后，请求方法为post

#6
#读取响应对象并decode()该对象，可转换编码
# response.read().decode('utf-8')

#7
# json，轻量级文本交换格式

def getcat():
    lengthValue = []
    lengthValue = g.multenterbox('请填写喵的尺寸','下载一只喵',['宽：','高：'])
    while True:
        if lengthValue == None:
            break

        width = lengthValue[0]
        height = lengthValue[1]
        if width.isdecimal() and height.isdecimal():
            savecat(width,height)
            break
        else:
            break

def savecat(w,h):
    response = urllib.request.urlopen(
        "http://placekitten.com/g/%s/%s" % (w, h))
    cat_img = response.read()

    cat_name = 'cat_%s_%s.jpg' % (w,h)
    data = g.filesavebox(default=cat_name)

    with open(data,'wb') as f:
        f.write(cat_img)


getcat()

def getcat2():
    msg = '请填写喵的尺寸'
    title = '下载一只喵'
    fieldNames =['宽：','高：']
    fieldValues = []
    size = width,height = 400, 600
    fieldValues = g.multenterbox(msg,title,fieldNames,size)

    while True:
        if fieldValues == None:
            break
        errmsg = ''

        try:
            width = int(fieldValues[0].strip())
            height = int(fieldValues[1].strip())
        except:
            errmsg += '宽高必须是整数'

        if errmsg == '':
            break
        fieldValues = g.multenterbox(errmsg,title,fieldNames,fieldValues)
    url = 'http://placekitten.com/g/%s/%s' % (width,height)

    response = urllib.request.urlopen(url)
    cat_img = response.read()

    filedir = g.diropenbox('请选择喵存放的文件夹')

    if filedir:
        filename = '%s/cat_%d_%d.jpg' % (filedir,width,height)
    else:
        filename = 'cat_%d_%d.jpg' % (width,height)

    with open(filename,'wb') as f:
        f.write(cat_img)


# getcat2()